import { Menu, message } from "antd";
import lessModule from "./index.module.less";
import { Fragment, useEffect, useState } from "react";
import HomePage_SystemSettingsPage_AccountManagementPage_SideMenuComponnet_MenuItemComponent from "./component/menuItem";
import { $Http } from "../../../../../../../../network";
import { $eventBus, $EventBus_off, $EventBus_on, $FilterOrganizationRank, $oganizationRankList } from "../../../../../../../../common/utils";


// 主页-账号管理页面-侧边菜单组件

const HomePage_SystemSettingsPage_AccountManagementPage_SideMenuComponnet: React.FC = (props) => {
    const [menuList, setMenuList] = useState<Array<object>>([])
    let [openKeysList, setOpenKeysList] = useState<Array<string>>([])
    let [selectKeysList, setSelectKeysList] = useState<Array<string>>([])
    const change_openMenu = (list: Array<string>) => {
        openKeysList = list
        setOpenKeysList([...list])
    }
    // 选中菜单
    const change_selectMenu = (data: object) => {
        selectKeysList = data["selectedKeys"]
        emit_organization(parseInt(data["key"].split("-")[1]))
        setSelectKeysList([...selectKeysList])        
    }

    const emit_organization = (id: number) => {
        setTimeout(() => {
            $eventBus.emit("selectedOrganization", { source: "HomePage_SystemSettingsPage_AccountManagementPage_SideMenuComponnet", explain: "请查询选中组织的用户", data: { id } })
        });
    }

    const recursion_menuModule = (sourceList: Array<object>, organization: Array<string> = []) => {
        return (
            sourceList.map((item) => {
                const level = parseInt(item["key"].split("-")[0])
                return (
                    <Fragment key={item["key"]}>
                        {
                            item["children"] && <Menu.SubMenu key={item["key"]} title={<HomePage_SystemSettingsPage_AccountManagementPage_SideMenuComponnet_MenuItemComponent id={item["id"]} level={level} name={item["label"]} isStatusIcon organization={organization} openKeysList={openKeysList} selectKeysList={selectKeysList} />}>
                                {
                                    recursion_menuModule(item["children"], [...organization, item["key"]])
                                }
                            </Menu.SubMenu>
                        }
                        {
                            !item["children"] && <Menu.Item key={item["key"]} >
                                <HomePage_SystemSettingsPage_AccountManagementPage_SideMenuComponnet_MenuItemComponent id={item["id"]} level={level} name={item["label"]} organization={organization} openKeysList={openKeysList} selectKeysList={selectKeysList} />
                            </Menu.Item>
                        }
                    </Fragment>
                )
            }
            )


        )
    }

    const http_userSearchOrganization = () => {
        $Http("search", { typeName: "系统设置/账号管理/组织管理" }).then((res) => {
            const menuList = res["list"]
            setMenuList([...menuList])
            // 该情况出现在初始化以及删除了当前选中的职位
            !selectKeysList.length && menuList.some((item: object) => {
                // 打开结构完整的第一个组织
                if (item["children"][0]?.["children"][0]) {
                    const teamData = item
                    const departmentData = teamData["children"][0]
                    const positionData = departmentData["children"][0]
                    openKeysList = Array.from(new Set([...openKeysList, teamData["key"], departmentData["key"]]))
                    selectKeysList = [positionData["key"]]
                    emit_organization(positionData["id"])
                    setOpenKeysList([...openKeysList])
                    setSelectKeysList([...selectKeysList])
                }
                return true
            });
        })
    }
    // 广播函数数据
    const eventBusFuncData = {
        // 更新组织
        updateOrganization: (data:object) => {
            http_userSearchOrganization()
        },
        // 确认删除
        confirmOperation: (data:object) => {
            const { rank, id } = data["data"]
            rank !== "账号" && $Http("delete", { typeName: "系统设置/账号管理/组织管理", id, name: data["data"]["name"], rank: $FilterOrganizationRank(rank) }).then((res) => {
                message.success(res["success"])
                const departmentIDList = res["departmentIDList"]?.map((item: number) => `1-${item}`)
                const positionIDList = res["positionIDList"]?.map((item: number) => `2-${item}`)
                // 从展开列表清除被删除的组织及其子组织
                openKeysList = data["data"]["openKeysList"].filter((item:string) => !departmentIDList.includes(item) && (rank === "团队" && item !== `0-${id}`))
                selectKeysList =  positionIDList.includes(data["data"]["selectKeysList"][0]) ? [] : selectKeysList
                setOpenKeysList([...openKeysList])
                setSelectKeysList([...selectKeysList])
                http_userSearchOrganization()
            })
        }
    }
    useEffect(() => {
        $EventBus_on(eventBusFuncData)
        http_userSearchOrganization()
        return () => {
            $EventBus_off(eventBusFuncData)
        }
    }, [])
    return (
        <div className={lessModule["homePageSystemSettingsPageAccountManagementPageSideMenuComponnet"]}>
            <Menu
                mode="inline"
                openKeys={openKeysList}
                selectedKeys={selectKeysList}
                expandIcon={false}
                onOpenChange={change_openMenu}
                onSelect={change_selectMenu}
            >
                {
                    recursion_menuModule(menuList)
                }
            </Menu>
        </div>
    )
}

export default HomePage_SystemSettingsPage_AccountManagementPage_SideMenuComponnet
